const express = require("express");
const { db } = require("../database");
const { ManagerAuth } = require("../middles");
const { validate, validators } = require("../validate");
const { query } = require("../logic");

const router = express.Router();
router.use(ManagerAuth);
router
  // 添加商品
  .post(
    "/",
    validate([validators.name, validators.description]),
    async (req, res) => {
      const {
        name,
        code,
        brand,
        description,
        material,
        sizes,
        colors,
        imgs,
        price,
        discount,
        category_id,
      } = req.body;
      const exist = await db.findOne("select * from Product where name = ?", [
        name,
      ]);
      if (exist)
        return res.send({ success: false, message: "该名称商品已存在！" });
      const results = await db.select(
        "insert into Product (name, code, brand, description, material, sizes, colors, imgs, price, discount, category_id, created_by_id, modified_by_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?)",
        [
          name,
          code,
          brand,
          description,
          material,
          JSON.stringify(sizes),
          JSON.stringify(colors),
          JSON.stringify(imgs),
          price,
          discount,
          category_id,
          req.user.id,
          req.user.id,
        ]
      );
      const object = await db.findOne(
        "select a.*, json_array(b.id, b.name) from Product a left join Category b on a.category_id = b.id where id = ?",
        [results.insertId]
      );
      res.send({ success: true, object });
    }
  )
  // 修改商品
  .put(
    "/:id",
    validate([validators.id, validators.description]),
    async (req, res) => {
      const {
        name,
        code,
        brand,
        description,
        material,
        sizes,
        colors,
        imgs,
        price,
        discount,
        category_id,
      } = req.body;
      let exist = await db.findOne("select * from Product where id = ?", [
        req.params.id,
      ]);
      if (!exist) return res.send({ success: false, message: "该分类不存在" });

      await db.query(
        "update Product set name = ?, code = ?, brand = ?, description = ?, material = ?, sizes = ?, colors = ?, imgs=?, price = ?, discount = ?, category_id = ?, modified_by_id = ?, modified_at = now() where id = ?",
        [
          name,
          code,
          brand,
          description,
          material,
          JSON.stringify(sizes),
          JSON.stringify(colors),
          JSON.stringify(imgs),
          price,
          discount,
          category_id,
          req.user.id,
          req.params.id,
        ]
      );

      const object = await db.findOne(
        "select a.*, json_array(b.id, b.name) as category from Product a left join Category b on a.category_id = b.id where a.id = ?",
        [req.params.id]
      );
      res.send({ success: true, object });
    }
  )
  // 查询产品
  .get(
    "/",
    validate([validators.limit, validators.offset]),
    async (req, res) => {
      res.send({
        success: true,
        query: await query(
          req,
          "Product a left join Category b on a.category_id = b.id",
          { fields: "a.*, json_array(b.id, b.name) category" }
        ),
      });
    }
  )
  // 外键查询
  .get("/fk", async (req, res) => {
    const { q } = req.query;
    const wheres = [
      `a.name like '%${q}%' or code like '${q}%' or a.description like '%${q}%'`,
    ];
    res.send({
      success: true,
      query: await query(
        req,
        "Product a left join Category b on a.category_id = b.id",
        { fields: "a.*, json_array(b.id, b.name) category", wheres }
      ),
    });
  });

//定义路由
const registerRouter = (app) => {
  app.use("/product", router);
};

module.exports = { registerRouter };
